const vscode = require('vscode')
const { reg } = require('./config.js')

function getUrl(options) {
  try {
    let activeText = getActivedText() || ''
    let url = ''
  
    if(!activeText) {
      return options.baseUrl
    }
  
    switch (options.title) {
      case 'vue2': 
        url = `${options.baseUrl}/#${activeText.replace(reg['.$'], 'vm-')}`
        break
      case 'element-ui': 
        url = `${options.baseUrl}/${activeText.replace(reg['el-'], '')}`
        break
      case 'NPM':
        url = `${options.baseUrl}/search?q=${activeText}`
        break
      case 'baidu':
        url = `${options.baseUrl}/s?wd=${activeText}`
        break
      case 'element-plus':
        url=`${options.baseUrl}/${activeText}.html`
      default: 
        url = options.baseUrl
    }
    return url || options.baseUrl
  } catch(err) {
    console.log('error', err)
  }
}

function getActivedText() {
  const activeTextEditor = vscode.window.activeTextEditor
  const { document, selection } = activeTextEditor || {}

  let selectText = ''
  // 当前行文本内容
  if (document) {
    if(selection.isSingleLine) {
      let curLineText = document.lineAt(selection.start.line).text
      selectText = curLineText.substring(selection.start.character, selection.end.character)
    }
  }
  return selectText.trim()
}

module.exports = { getUrl, getActivedText }